package com.gmtx.syb.home.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gmtx.syb.R;
import com.gmtx.syb.application.MyApplication;
import com.gmtx.syb.bean.GoodsBean;
import com.gmtx.syb.bean.HomePagePropBean;
import com.gmtx.syb.bean.IndexAdBean;
import com.gmtx.syb.utils.DateUtil;
import com.squareup.picasso.Picasso;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 多布局RecyclerView适配器
 * Created by Sun on 2016/11/7.
 */

public class HomePageDataAdapter extends RecyclerView.Adapter<HomePageDataAdapter.MyViewHolder>  {
    private List<IndexAdBean.ResultBean> list_pager;
    private List<GoodsBean.ResultBean.DailySelectionGoodsBean> list_daliy;
    private HomePagePropBean homePagePropBean;
    private Context context;
    private LayoutInflater inflater;
    private int[] ids = new int[]{
            R.layout.layout_home_head,
            R.layout.layout_home_navi,
            R.layout.layout_recommend_home,
            R.layout.layout_title_list_home,
            R.layout.item_daily_home,
            R.layout.item_foot_list_home
    };
    private RecyclerView recyclerView;

    public HomePageDataAdapter(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    public void addRoundPageData(List<IndexAdBean.ResultBean> list){
        this.list_pager = list;
        notifyDataSetChanged();
    }

    public void setDaliyData(List<GoodsBean.ResultBean.DailySelectionGoodsBean> list_daliy){
        this.list_daliy = new ArrayList<>();
        this.list_daliy.addAll(list_daliy);
        notifyDataSetChanged();
    }

    public void addDaliyData(List<GoodsBean.ResultBean.DailySelectionGoodsBean> list_daliy_add){
        if (this.list_daliy != null) {
            this.list_daliy.addAll(list_daliy_add);
            notifyDataSetChanged();
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    public void setHomePagePropMode(HomePagePropBean homePagePropBean){
        this.homePagePropBean = homePagePropBean;
        notifyDataSetChanged();
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        MyViewHolder viewHolder;
        switch (viewType) {
            case 0:
                view = inflater.inflate(ids[0],parent,false);
                viewHolder =  new MyViewHolder(view);
                viewHolder.setType(0);
                return viewHolder;
            case 1:
                view = inflater.inflate(ids[1],parent,false);
                viewHolder =  new MyViewHolder(view);
                viewHolder.setType(1);
                return viewHolder;
            case 2:
                view = inflater.inflate(ids[2],parent,false);
                viewHolder =  new MyViewHolder(view);
                viewHolder.setType(2);
                return viewHolder;
            case 3:
                view = inflater.inflate(ids[3],parent,false);
                viewHolder =  new MyViewHolder(view);
                viewHolder.setType(3);
                return viewHolder;
            case 4:
                view = inflater.inflate(ids[4],parent,false);
                viewHolder =  new MyViewHolder(view);
                viewHolder.setType(4);
                return viewHolder;
            case 5:
                view = inflater.inflate(ids[5],parent,false);
                viewHolder = new MyViewHolder(view);
                viewHolder.setType(5);
                return viewHolder;
        }
        return null;
    }


    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        switch (holder.getType()) {
            case 0:
                if (holder.vp.getChildCount() > 0) {
                    return;
                }
                RoundPageAdapter roundPageAdapter = new RoundPageAdapter(list_pager, context);
                holder.vp.setAdapter(roundPageAdapter);
                for (int i = 0; i < list_pager.size(); i++) {
                    ImageView imageView = new ImageView(context);
                    imageView.setBackgroundResource(R.drawable.point_home_grey);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(10,20,5,20);
                    holder.container_vp_home.addView(imageView,layoutParams);
                }
                holder.container_vp_home.getChildAt(0).setBackgroundResource(R.drawable.point_home_white);
                holder.vp.addOnPageChangeListener(holder);
                holder.handler.sendEmptyMessageDelayed(200,3000);
                break;
            case 1:
//                holder.iv_score_navi_home.setOnClickListener(this);
//                holder.iv_certify_navi_home.setOnClickListener(this);
//                holder.iv_theme_navi_home.setOnClickListener(this);
//                holder.iv_noob_navi_home.setOnClickListener(this);

                break;
            case 2:
                if (homePagePropBean == null || !TextUtils.isEmpty(holder.tv_hour_rec_home.getText())) {
                    return;
                }
                HomePagePropBean.ResultBean resultBean = homePagePropBean.getResult().get(0);
//                FinalBitmap.create(context).display(holder.iv_icon_jh_recommend_home,resultBean.getJuhuishijian_ico(),
//                        ((LMFragmentActivity) context).loadingBitmap, ((LMFragmentActivity) context).loadingBitmap);
//                FinalBitmap.create(context).display(holder.iv_content_jh_recommend_home,resultBean.getJuhuishijian_pic(),
//                        ((LMFragmentActivity) context).loadingBitmap, ((LMFragmentActivity) context).loadingBitmap);
//                FinalBitmap.create(context).display(holder.iv_good_jh_recommend_home,resultBean.getShangpinhui_ico(),
//                        ((LMFragmentActivity) context).loadingBitmap, ((LMFragmentActivity) context).loadingBitmap);
//                FinalBitmap.create(context).display(holder.iv_content_good_jh_recommend_home,resultBean.getShangpinhui_pic(),
//                        ((LMFragmentActivity) context).loadingBitmap, ((LMFragmentActivity) context).loadingBitmap);
//                FinalBitmap.create(context).display(holder.iv_brand_jh_recommend_home,resultBean.getPinpaihui_ico(),
//                        ((LMFragmentActivity) context).loadingBitmap, ((LMFragmentActivity) context).loadingBitmap);
//                FinalBitmap.create(context).display(holder.iv_content_brand_jh_recommend_home,resultBean.getPinpaihui_pic(),
//                        ((LMFragmentActivity) context).loadingBitmap, ((LMFragmentActivity) context).loadingBitmap);

                Picasso.with(context).load(resultBean.getJuhuishijian_ico()).into(holder.iv_icon_jh_recommend_home);
                Picasso.with(context).load(resultBean.getJuhuishijian_pic()).into(holder.iv_content_jh_recommend_home);
                Picasso.with(context).load(resultBean.getShangpinhui_ico()).into(holder.iv_good_jh_recommend_home);
                Picasso.with(context).load(resultBean.getShangpinhui_pic()).into(holder.iv_content_good_jh_recommend_home);
                Picasso.with(context).load(resultBean.getPinpaihui_ico()).into(holder.iv_brand_jh_recommend_home);
                Picasso.with(context).load(resultBean.getPinpaihui_pic()).into(holder.iv_content_brand_jh_recommend_home);

                holder.tv_desc_jh_recommend_home.setText(resultBean.getJuhuishijian_str());
                holder.tv_good_jh_recommend_home.setText(resultBean.getShangpinhui_title());
                holder.tv_brand_jh_recommend_home.setText(resultBean.getPinpaihui_title());
                holder.tv_desc_good_jh_recommend_home.setText(resultBean.getShangpinhui_str());
                holder.tv_desc_brand_jh_recommend_home.setText(resultBean.getPinpaihui_str());
                holder.tv_time_jh_recommend_home.setText(resultBean.getTitle());
//                holder.container_jh.setOnClickListener(this);
//                holder.container_brand_home.setOnClickListener(this);
//                holder.container_goods_jh.setOnClickListener(this);

                //聚会时间倒计时
                String begin_date = resultBean.getBegin_date();
                String end_date = resultBean.getEnd_date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                try {
                    Date begin = simpleDateFormat.parse(begin_date);
                    Date end = simpleDateFormat.parse(end_date);
                    long l1 = System.currentTimeMillis();
                    long l = (begin.getTime() - l1) / 1000;
                    if (l > 0) {
                        holder.tv_info_jhsj.setVisibility(View.VISIBLE);
                        holder.tv_info_jhsj.setText("距开始");
                        MyApplication.time = l;
                        long mTime = MyApplication.time;
                        holder.tv_hour_rec_home.setText(String.format("%02d", DateUtil.getHour(mTime)));
                        holder.tv_minute_rec_home.setText(String.format("%02d",DateUtil.getMinute(mTime)));
                        holder.tv_second_rec_home.setText(String.format("%02d",DateUtil.getSecond(mTime)));
                        holder.handler.sendEmptyMessage(100);
                    }else{
                        long l2 = end.getTime() - l1;
                        if(l2 > 0){
                            holder.tv_info_jhsj.setVisibility(View.VISIBLE);
                            holder.tv_info_jhsj.setText("距结束");
                            MyApplication.time = l2 / 1000;
                            long mTime = MyApplication.time;
                            holder.tv_hour_rec_home.setTextColor(Color.RED);
                            holder.tv_minute_rec_home.setTextColor(Color.RED);
                            holder.tv_second_rec_home.setTextColor(Color.RED);
                            holder.tv_hour_rec_home.setText(String.format("%02d",DateUtil.getHour(mTime)));
                            holder.tv_minute_rec_home.setText(String.format("%02d",DateUtil.getMinute(mTime)));
                            holder.tv_second_rec_home.setText(String.format("%02d",DateUtil.getSecond(mTime)));
                            holder.handler.sendEmptyMessage(100);
                        }else{
                            holder.container_time.setVisibility(View.GONE);
                            holder.tv_over_jh.setVisibility(View.VISIBLE);
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                break;
            case 3:
                break;
            case 4:
                GoodsBean.ResultBean.DailySelectionGoodsBean mode = list_daliy.get(position - 4);
//                FinalBitmap.create(context).display(holder.listoftitle_img, mode.getGoods_img_url(),
//                        ((LMFragmentActivity) context).loadingBitmap, ((LMFragmentActivity) context).loadingBitmap);
                Picasso.with(context).load(mode.getGoods_img_url()).into(holder.listoftitle_img);
                View container = (View) holder.listoftitle_img.getParent();
                container.setTag(position - 4);
                //container.setOnClickListener(this);
                holder.listoftitle_title.setText(mode.getGoods_name() == null ? "" : mode.getGoods_name());
                holder.listoftitle_money.setText(String.format("%.2f", Double.parseDouble((mode.getGoods_price() == null || mode.getGoods_price().equals("")) ? "0" : mode.getGoods_price())));
                holder.listoftitle_jifen.setText(String.format("%.2f", Double.parseDouble((mode.getRevert_point() == null || mode.getRevert_point().equals("")) ? "0" : mode.getRevert_point())));
                holder.listoftitle_money_delete.setText("¥" + (mode.getGoods_reserve_price() == null ? 0 : mode.getGoods_reserve_price()));
                holder.listoftitle_money_delete.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                holder.listoftitle_getPrice.setText(String.format("%.2f", Double.parseDouble((mode.getGet_price() == null || mode.getGet_price().equals("")) ? "0" : mode.getGet_price())));
                holder.listoftitle_discription.setText(mode.getGoods_desc() == null ? "" : mode.getGoods_desc());

                break;
            case 5:

                break;
        }
    }


//    public void onClick(View view){
//        switch (view.getId()) {
//            case R.id.iv_noob_navi_home:
//                if (LMApplication.sysConfig_mode == null) {
//                    Toast.makeText(context, "数据未加载请稍后", Toast.LENGTH_SHORT).show();
//                }else{
//                    ((LMFragmentActivity) context).startLMActivity(NoobActivity.class);
//                }
//                break;
//            case R.id.iv_score_navi_home:
//                if (LMTool.user.isok()) {
//                    context.startActivity(MyPointsActivity.getCallingIntent(context));
//                } else {
//                    ((LMFragmentActivity) context).startLMActivity(NewLoadingActivity.class);
//                }
//                break;
//            case R.id.iv_certify_navi_home:
//                Intent intent = new Intent(context, CertificationActivity.class);
//                context.startActivity(intent);
//                break;
//            case R.id.iv_theme_navi_home:
//                context.startActivity(new Intent(context, SubjectActivity.class));
//                break;
//            case R.id.container_jh:
//                //打开聚惠时间的WebView Activity
//                Intent jh = RXGoodsWebViewActivity.getCallingIntent(context, "http://119.29.35.239:8801/yg-rest/rest/juhui/juhuiList", "聚惠时间");
//                context.startActivity(jh);
//                break;
//            case R.id.container_list_home:
//                try {
//                    int position = (int) view.getTag();
//                    DaliyMode.ResultBean.DailySelectionGoodsBean bean = list_daliy.get(position);
//                    TransitUtil.showItemDetailPage(context, bean.getGoods_id());
//                } catch (Exception e) {
////                    ((LMFragmentActivity) activity).toast("position"+position);
//                    Log.e("HomePageDataAdapter", "onClick: ",e );
//                }
//                break;
//            case R.id.container_brand_home:
//                context.startActivity(new Intent(context, BrandActivity.class));
//                break;
//            case R.id.container_goods_jh:
//                context.startActivity(new Intent(context, GoodsActivity.class));
//                break;
//        }
//    }




    @Override
    public int getItemCount() {
        int count = 0;
        //控制并发
        if (list_pager != null && homePagePropBean != null) {
            count += 5;
        }

        if (list_daliy != null) {
            count += list_daliy.size();
        }
        return count;
    }

    @Override
    public int getItemViewType(int position) {
        if(position == getItemCount() - 1){
            return 5;
        }
        if (position > 3) {
            return 4;
        }
        switch (position) {
            case 0:
                return 0;
            case 1:
                return 1;
            case 2:
                return 2;
            case 3:
                return 3;
        }
        return -1;
    }

    public void loginFinished(){
        View view = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
        view.findViewById(R.id.pb_loading).setVisibility(View.GONE);
        view.findViewById(R.id.tv_msg_finished).setVisibility(View.VISIBLE);

    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements ViewPager.OnPageChangeListener {

        @BindView(R.id.iv_noob_navi_home)
        @Nullable
        ImageView iv_noob_navi_home;
        @BindView(R.id.iv_score_navi_home)
        @Nullable
        ImageView iv_score_navi_home;
        @BindView(R.id.iv_certify_navi_home)
        @Nullable
        ImageView iv_certify_navi_home;
        @BindView(R.id.iv_theme_navi_home)
        @Nullable
        ImageView iv_theme_navi_home;

        @BindView(R.id.listoftitle_img)
        @Nullable
        ImageView listoftitle_img;
        @BindView(R.id.listoftitle_title)
        @Nullable

        TextView listoftitle_title;
        @BindView(R.id.listoftitle_money)
        @Nullable
        TextView listoftitle_money;
        @BindView(R.id.listoftitle_money_delete)
        @Nullable
        TextView listoftitle_money_delete;
        @BindView(R.id.listoftitle_jifen)
        @Nullable
        TextView listoftitle_jifen;
        @BindView(R.id.listoftitle_getPrice)
        @Nullable
        TextView listoftitle_getPrice;
        @BindView(R.id.listoftitle_discription)
        @Nullable
        TextView listoftitle_discription;

        @BindView(R.id.container_vp_home)
        @Nullable
        LinearLayout container_vp_home;

        @BindView(R.id.iv_icon_jh_recommend_home)
        @Nullable
        ImageView iv_icon_jh_recommend_home;
        @BindView(R.id.iv_good_jh_recommend_home)
        @Nullable
        ImageView iv_good_jh_recommend_home;
        @BindView(R.id.iv_brand_jh_recommend_home)
        @Nullable
        ImageView iv_brand_jh_recommend_home;
        @BindView(R.id.iv_content_jh_recommend_home)
        @Nullable
        ImageView iv_content_jh_recommend_home;
        @BindView(R.id.iv_content_good_jh_recommend_home)
        @Nullable
        ImageView iv_content_good_jh_recommend_home;
        @BindView(R.id.iv_content_brand_jh_recommend_home)
        @Nullable
        ImageView iv_content_brand_jh_recommend_home;

        @BindView(R.id.time_jh_recommend_home)
        @Nullable
        TextView tv_time_jh_recommend_home;
        @BindView(R.id.tv_good_jh_recommend_home)
        @Nullable
        TextView tv_good_jh_recommend_home;
        @BindView(R.id.tv_brand_jh_recommend_home)
        @Nullable
        TextView tv_brand_jh_recommend_home;
        @BindView(R.id.tv_desc_good_jh_recommend_home)
        @Nullable
        TextView tv_desc_good_jh_recommend_home;
        @BindView(R.id.tv_desc_brand_jh_recommend_home)
        @Nullable
        TextView tv_desc_brand_jh_recommend_home;
        @BindView(R.id.tv_desc_jh_recommend_home)
        @Nullable
        TextView tv_desc_jh_recommend_home;
        @BindView(R.id.container_jh)
        @Nullable
        LinearLayout container_jh;
        @BindView(R.id.container_brand_home)
        @Nullable
        RelativeLayout container_brand_home;
        @BindView(R.id.container_goods_jh)
        @Nullable
        RelativeLayout container_goods_jh;

        @BindView(R.id.container_time)
        @Nullable
        LinearLayout container_time;
        @BindView(R.id.tv_over_jh)
        @Nullable
        TextView tv_over_jh;

        @BindView(R.id.tv_hour_rec_home)
        @Nullable
        TextView tv_hour_rec_home;
        @BindView(R.id.tv_minute_rec_home)
        @Nullable
        TextView tv_minute_rec_home;
        @BindView(R.id.tv_second_rec_home)
        @Nullable
        TextView tv_second_rec_home;
        @BindView(R.id.tv_info_jhsj)
        @Nullable
        TextView tv_info_jhsj;



        ViewPager vp;
        //item类型
        private int type;
        //当前轮播位置
        private int mPosition = 0;

        private Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    //计时器消息
                    case 100:
                        long mTime = -- MyApplication.time;
                        tv_hour_rec_home.setText(String.format("%02d",DateUtil.getHour(mTime)));
                        tv_minute_rec_home.setText(String.format("%02d",DateUtil.getMinute(mTime)));
                        tv_second_rec_home.setText(String.format("%02d",DateUtil.getSecond(mTime)));
                        if(mTime > 0){
                            handler.sendEmptyMessageDelayed(100,1000);
                        }
                        break;
                    //自动轮播消息
                    case 200:
                        int currentPosition = vp.getCurrentItem();
                        if(currentPosition + 1 > vp.getChildCount() - 1){
                            currentPosition = 0;
                            vp.setCurrentItem(currentPosition);
                        }else{
                            currentPosition ++;
                            vp.setCurrentItem(currentPosition);
                        }
                        sendEmptyMessageDelayed(200,3000);
                        break;
                }
            }
        };

        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            vp = (ViewPager) itemView.findViewById(R.id.vp_homepage);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        @Override
        public void onPageSelected(int position) {
//            for (int i = 0; i < container_vp_home.getChildCount(); i++) {
//                View childAt = container_vp_home.getChildAt(position);
//                if (i == position) {
//                    childAt.setBackgroundResource(R.drawable.point_home_white);
//                }else{
//                    childAt.setBackgroundResource(R.drawable.point_home_grey);
//                }
//            }
            container_vp_home.getChildAt(position).setBackgroundResource(R.drawable.point_home_white);
            container_vp_home.getChildAt(mPosition).setBackgroundResource(R.drawable.point_home_grey);
            mPosition = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

}
